/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  pickedFaceData
} from '@amcax/base'
import {
  previewer
} from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj, previewData } from '@app-cad/common/utils/render';
import { wsApi } from '@app-cad/server';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useMemo, useState } from 'react';

type FormData = {
  surface: pickedFaceData;
};

type Params = {
  surface: string;
};

function ExplodeSurface({
  title,
  onClose,
  placement,
  props,
}: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({
    surface: null,
  });
  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({
        surface: null,
      });
      return;
    }

    const { surface } = props.params;

    const surfaceObj =
      surface && (picker.generatePickObjByPickID(surface) as pickedFaceData);

    const datas = {
      surface: surfaceObj,
    };

    setFormData(datas);
  }, []);

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }
    await execute(true);
  }, [formData]);

  const isFormDataValid = () => {
    const { surface } = formData;

    return surface !== null;
  };
  const finishValid = useMemo(isFormDataValid, [formData]);
  const execute = async (preview: boolean = false) => {
    const { surface } = formData;
    const surfaceID: string = getIdOfPickedObj(surface);

    const params: Params = {
      surface: surfaceID,
    };
    const res =
      props == null
        ? await wsApi.explodeSurface(params, preview)
        : await wsApi.setParams(props.shape, params, preview);

    if (preview) {
      await previewData(res);
    }

    return res;
  };

  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute();

    exit();
  };

  const exit = () => {
    previewer.clear();
    onClose();
  };

  // =================

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      surface: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
    },
  };

  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={false}
      onClose={exit}
      title={title}
      placement={placement}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surface: {
          'ui:placeholder': '请输入曲面',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
    />
  );
}

export const cmdExplodeSurface: CurvedBaseCommand = {
  id: 'cmdExplodeSurface',
  label: 'command.explode-surface',
  icon: 'commands/curved/explode-surface',
  create: (label, onClose, props) => (
    <ExplodeSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
